package com.wm.machine.baselibrary.utils.okhttp.exceptions;

import android.util.Log;

import com.google.gson.JsonIOException;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;

/**
 * Copyright
 * author zhengcheng
 * date 2018/4/2
 * describe 异常处理类
 * history
 */

public class HttpExceptionManager {

    private static final String TAG = "HttpExceptionManager";

    public HttpApiException handleException(Throwable throwable){
        HttpApiException httpApiException;
        Log.e(TAG, throwable.getMessage());
        if (throwable instanceof HttpServerException){
            httpApiException= new HttpApiException(throwable, ExceptionEnum.SERVER_ERROR.getCode());
            httpApiException.setDisplayMessage("服务器异常");
            return httpApiException;
        } else if (throwable instanceof JSONException || throwable instanceof JsonSyntaxException
                || throwable instanceof JsonIOException || throwable instanceof JsonParseException
                || throwable instanceof ParseException){
            httpApiException = new HttpApiException(throwable, ExceptionEnum.PARSE_ERROR.getCode());
            httpApiException.setDisplayMessage("数据解析异常");
            return httpApiException;
        } else if (throwable instanceof ConnectException || throwable instanceof UnknownHostException) {
            httpApiException = new HttpApiException(throwable, ExceptionEnum.NETWORK_ERROR.getCode());
            httpApiException.setDisplayMessage("网络连接异常");
             return httpApiException;
        } else if (throwable instanceof SocketTimeoutException){
            httpApiException = new HttpApiException(throwable, ExceptionEnum.TIMEOUT_ERROR.getCode());
            httpApiException.setDisplayMessage("网络连接超时");
            return httpApiException;
        } else {
            httpApiException = new HttpApiException(throwable, ExceptionEnum.UNKNOW.getCode());
            httpApiException.setDisplayMessage("未知错误");
            return httpApiException;
        }

    }
}
